package com.by.service.impl;

import com.by.api.StockClient;
import com.by.bean.Order;
import com.by.mapper.OrderDetailMapper;
import com.by.mapper.OrderMapper;
import com.by.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.attribute.standard.MediaSize;

import java.sql.SQLSyntaxErrorException;
import java.util.Iterator;

import static com.by.utils.Assert.ISFAIL;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    StockClient stockClient;

    /**
     * 生成订单 订单明细  更新库存
     *
     * @param order
     * @return
     */
   // @Transactional
    @GlobalTransactional//(noRollbackFor = SQLSyntaxErrorException.class) //全局事务
    @Override
    public int save(Order order) {
        //保存订单
        int rs = orderMapper.save(order);
        ISFAIL(rs, "生成订单失败");

        //更新库存
        if (null != order.getOrderDeailList() && order.getOrderDeailList().size() > 0) {
            order.getOrderDeailList().forEach(el -> {
                stockClient.updateStock(el.getGid(), el.getNum());
            });
        }

        //成功
        if (null != order.getOrderDeailList() && order.getOrderDeailList().size() > 0) {
            //保存明细
            rs = orderDetailMapper.batchSave(order.getId(), order.getOrderDeailList());
            ISFAIL(rs, "生成订单明细失败");

        }


        return 1;
    }
}
